package Cau10;

import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics2D;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.net.DatagramPacket;
import java.net.DatagramSocket;

import javax.swing.JFrame;
import javax.swing.JPanel;


public class BlackBoardServer extends JPanel {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	DatagramPacket packet;
	DatagramSocket socket;

	public BlackBoardServer(int port) {
		try {
			socket = new DatagramSocket(port);
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	public Line getObjectFromPacket(DatagramPacket dp) {
		try {
			ByteArrayInputStream byteStream = new ByteArrayInputStream(
					dp.getData());
			ObjectInputStream ois = new ObjectInputStream(byteStream);
			Line line = (Line) ois.readObject();
			return line;

		} catch (Exception e) {
			e.printStackTrace();

		}
		return null;

	}

	public void displayObject(Line p) {
		System.out.println("X1 = " + p.get_sPoint().x + "; Y1 = "
				+ p.get_sPoint().y + "\tX2 = " + p.get_ePoint().x + "; Y2 = "
				+ p.get_ePoint().y);
	}

	public void run() {
		byte[] buffer = new byte[1024];
		packet = new DatagramPacket(buffer, buffer.length);
		boolean cont = true;
		Graphics2D g = (Graphics2D) this.getGraphics();
		try {
			// socket.receive(packet);
			// bai2_pointObject p = getObjectFromPacket(packet);
			// displayObject(p);
			// x1 = p.getX();
			// y1 = p.getY();
			while (cont) {
				socket.receive(packet);

				Line line = new Line();
				line = getObjectFromPacket(packet);

				// displayObject(line);
				Float size = line.getSize();
				Color color = line.getColor();
				BasicStroke bstr = new BasicStroke(size);
				g.setStroke(bstr);
				g.setColor(color);
				g.setPaintMode();
				// g.setXORMode(getBackground());
				g.drawLine(line.get_sPoint().x, line.get_sPoint().y,
						line.get_ePoint().x, line.get_ePoint().y);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@SuppressWarnings("deprecation")
	public static void main(String[] args) {
		JFrame win = new JFrame("Blackboard Server");
		win.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		win.setSize(800, 600);
		win.setVisible(true);
		BlackBoardServer server = new BlackBoardServer(5000);
		win.setContentPane(server);
		win.show();
		server.run();
	}

}
